import React, { useState, useEffect, useContext } from 'react';
import { Link } from 'react-router-dom';
import { AuthContext } from '../contexts/AuthContext';
import { articleService, userService } from '../services/api';
import { BsPersonCircle, BsPencil, BsEye, BsHeart, BsChat } from 'react-icons/bs';
import ArticleCard from '../components/article/ArticleCard';

const Profile = () => {
  const { user, updateUserInfo } = useContext(AuthContext);
  const [userInfo, setUserInfo] = useState(null);
  const [articles, setArticles] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [editMode, setEditMode] = useState(false);
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    bio: ''
  });

  useEffect(() => {
    const fetchUserData = async () => {
      try {
        const response = await userService.getCurrentUser();
        setUserInfo(response.data);
        setFormData({
          username: response.data.username,
          email: response.data.email,
          bio: response.data.bio || ''
        });
      } catch (err) {
        setError('获取用户信息失败');
      }
    };

    const fetchUserArticles = async () => {
      try {
        if (user) {
          const response = await articleService.getUserArticles(user.id);
          setArticles(response.data.content);
        }
      } catch (err) {
        console.error('获取用户文章失败', err);
      } finally {
        setLoading(false);
      }
    };

    fetchUserData();
    fetchUserArticles();
  }, [user]);

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData({
      ...formData,
      [name]: value
    });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await updateUserInfo(formData);
      setEditMode(false);
      // 刷新用户信息
      const response = await userService.getCurrentUser();
      setUserInfo(response.data);
    } catch (err) {
      setError('更新用户信息失败');
    }
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center py-20">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary-600"></div>
      </div>
    );
  }

  if (error || !userInfo) {
    return (
      <div className="bg-red-100 text-red-800 p-4 rounded-md">
        {error || '无法加载用户信息'}
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto">
      <div className="bg-white dark:bg-dark-800 rounded-lg shadow-md overflow-hidden mb-8">
        <div className="px-6 py-8">
          <div className="flex items-start">
            <div className="mr-6">
              {userInfo.avatar ? (
                <img
                  src={userInfo.avatar}
                  alt={userInfo.username}
                  className="w-32 h-32 rounded-full"
                />
              ) : (
                <BsPersonCircle className="w-32 h-32 text-gray-400" />
              )}
            </div>
            
            {!editMode ? (
              <div className="flex-1">
                <div className="flex justify-between items-center">
                  <h1 className="text-2xl font-bold text-dark-800 dark:text-dark-200">
                    {userInfo.username}
                  </h1>
                  <button
                    onClick={() => setEditMode(true)}
                    className="flex items-center text-primary-600 dark:text-primary-400 hover:text-primary-700 dark:hover:text-primary-300"
                  >
                    <BsPencil className="mr-1" />
                    编辑资料
                  </button>
                </div>
                <p className="text-gray-600 dark:text-gray-400 mb-4">{userInfo.email}</p>
                <p className="text-dark-600 dark:text-dark-300 mb-6">
                  {userInfo.bio || '这个人很懒，什么都没留下...'}
                </p>
                <div className="flex space-x-4 text-sm text-dark-500 dark:text-dark-400">
                  <div className="flex items-center">
                    <span className="font-medium mr-2">{userInfo.articleCount}</span>
                    <span>文章</span>
                  </div>
                  <div className="flex items-center">
                    <span className="font-medium mr-2">{userInfo.commentCount}</span>
                    <span>评论</span>
                  </div>
                  <div className="flex items-center">
                    <span className="font-medium mr-2">{userInfo.subscriberCount}</span>
                    <span>粉丝</span>
                  </div>
                </div>
              </div>
            ) : (
              <form onSubmit={handleSubmit} className="flex-1">
                <div className="mb-4">
                  <label className="label" htmlFor="username">
                    用户名
                  </label>
                  <input
                    type="text"
                    id="username"
                    name="username"
                    value={formData.username}
                    onChange={handleInputChange}
                    className="input"
                    required
                  />
                </div>
                <div className="mb-4">
                  <label className="label" htmlFor="email">
                    邮箱
                  </label>
                  <input
                    type="email"
                    id="email"
                    name="email"
                    value={formData.email}
                    onChange={handleInputChange}
                    className="input"
                    required
                  />
                </div>
                <div className="mb-6">
                  <label className="label" htmlFor="bio">
                    个人简介
                  </label>
                  <textarea
                    id="bio"
                    name="bio"
                    value={formData.bio}
                    onChange={handleInputChange}
                    className="input h-24 resize-none"
                  ></textarea>
                </div>
                <div className="flex space-x-3">
                  <button
                    type="submit"
                    className="btn btn-primary"
                  >
                    保存更改
                  </button>
                  <button
                    type="button"
                    onClick={() => setEditMode(false)}
                    className="btn btn-outline"
                  >
                    取消
                  </button>
                </div>
              </form>
            )}
          </div>
        </div>
      </div>

      <div className="mb-8">
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-xl font-bold text-dark-800 dark:text-dark-200">
            我的文章
          </h2>
          <Link
            to="/articles/new"
            className="btn btn-primary"
          >
            写文章
          </Link>
        </div>

        {articles.length > 0 ? (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {articles.map(article => (
              <ArticleCard key={article.id} article={article} />
            ))}
          </div>
        ) : (
          <div className="bg-gray-100 dark:bg-dark-700 p-8 rounded-lg text-center">
            <p className="text-dark-600 dark:text-dark-300 mb-4">
              你还没有发布任何文章
            </p>
            <Link
              to="/articles/new"
              className="btn btn-primary"
            >
              写第一篇文章
            </Link>
          </div>
        )}
      </div>
    </div>
  );
};

export default Profile; 